<template>
    <div class="white-box">
        <title-more title="短信群发设置" />
        <cell-tip
            tip="短信群发可能会有1～2小时的延迟，具体看短信运营商的网络情况，请合理安排发送时间，单条短信不能超过255个字，超过70字就是长短信，按67字一条计费; 群发之前请先用手机号码测试一下！"
            bottom="20px"
        />
        <div class="sms-one">
            当前可用短信数量：<strong>{{ sms_nums }}</strong
            >条
            <el-button type="primary" size="small" @click="clickRecharge">立即充值</el-button>
            <!-- <el-popover placement="right" content="您好，暂不支持用户线上充值，请联系您的服务经理进行充值。" :width="280" trigger="click">
                <template #reference>
                    <el-button type="primary" size="small">立即充值</el-button>
                </template>
            </el-popover> -->
        </div>

        <el-tabs v-model="tabName" @tab-click="clickTab">
            <el-tab-pane label="短信群发" name="0">
                <div class="tab-sms">
                    <div class="tab-sms__left">
                        <div class="tel-head">
                            <i class="tel-head-one"></i>
                            <div class="tel-head-two"></div>
                        </div>
                        <div class="tel-body">
                            <div class="tel-body-item" v-if="sms_text">{{ sms_text }}</div>
                        </div>
                        <div class="tel-foot"></div>
                    </div>
                    <div class="tab-sms__right">
                        <div>
                            <detail-item bottom="20px" title="发送方式" title-color="#333" weight="600">
                                <el-radio-group v-model="radio_type" @change="radioChange">
                                    <el-radio label="0">平台会员</el-radio>
                                    <el-radio label="1">导入手机号</el-radio>
                                </el-radio-group>
                            </detail-item>
                            <detail-item class="exp-detail" bottom="20px" title="发送用户" title-color="#333" weight="600" v-if="radio_type == 0">
                                <el-select v-model="level_id" clearable placeholder="请选择会员等级">
                                    <el-option :label="item.level_name" :value="item.grade_id" v-for="item in level_arrs" :key="item.grade_id" />
                                </el-select>
                            </detail-item>
                            <detail-item class="sms-btns" bottom="20px" title="导入手机号" title-color="#333" weight="600" v-if="radio_type == 1">
                                <div class="sms-btns__box">
                                    <el-upload
                                        ref="uploadFileRef"
                                        accept=".xlsx,.xls,.csv"
                                        :file-list="fileList_two"
                                        :action="actionImgUrl()"
                                        :auto-upload="false"
                                        :limit="1"
                                        :on-exceed="handleExceed_two"
                                        :on-remove="handleRemove_two"
                                        :on-change="fileChange_two"
                                    >
                                        <template #trigger>
                                            <el-button type="primary">选择文件</el-button>
                                        </template>
                                        <el-button class="downs" type="warning" @click.stop="uploadFile">上传导入</el-button>
                                        <el-button class="downs" type="warning" @click.stop="downExcel">下载模板</el-button>
                                    </el-upload>
                                </div>

                                <div class="input-tips">请上传*.xlsx; *.xls; *.csv格式的文件</div>
                            </detail-item>
                            <detail-item class="sms-btns" bottom="20px" title="文件内容" title-color="#333" weight="600" v-if="radio_type == 1">
                                <el-input v-model.trim="sms_tel" type="textarea" :rows="9" show-word-limit placeholder="格式为13888888888,18888888888" />
                                <div class="input-tips">以英文输入法中的逗号<code>,</code>分割手机号，最后一个手机号结尾<code>不加逗号</code></div>
                            </detail-item>
                            <detail-item bottom="10px" title="编辑内容" title-color="#333" weight="600">
                                <el-input
                                    v-model.trim="sms_text"
                                    class="sms-textarea"
                                    type="textarea"
                                    :rows="10"
                                    maxlength="255"
                                    show-word-limit
                                    placeholder="请输入内容"
                                />
                                <div class="input-tips">编辑内容不要包含有<code>【】</code>符号</div>
                            </detail-item>
                            <detail-item bottom="20px" v-if="radio_type == 0">
                                <div class="tab-sms__word">
                                    <div class="tab-sms__word-item" v-for="(item, index) in sms_words" :key="index" @click="clickWord(item)">
                                        {{ item.text }}
                                    </div>
                                </div>
                            </detail-item>
                        </div>
                        <i class="arrow arrow_out"></i>
                        <i class="arrow arrow_in"></i>
                    </div>
                </div>

                <div class="foot-btn flexs-center">
                    <el-button type="primary" size="large" :loading="btn_loading" @click="handleSend">发送</el-button>
                </div>
            </el-tab-pane>
            <el-tab-pane label="群发记录" name="1">
                <el-table
                    class="table-mb"
                    v-loading="loading"
                    :data="arr_data"
                    :header-cell-style="{ background: '#F5F7FA' }"
                    element-loading-background="rgba(255, 255, 255, 0.6)"
                >
                    <el-table-column prop="content" label="内容" min-width="400"></el-table-column>
                    <el-table-column prop="send_num" label="发送条数" min-width="160"></el-table-column>
                    <el-table-column prop="created_at_label" label="发送时间" min-width="160"></el-table-column>
                    <el-table-column label="状态" width="160">
                        <template #default="{ row }">
                            <span style="color: #4b93fa" v-if="row.status == 0">发送中</span>
                            <span style="color: #4b93fa" v-else>{{ row.status == 1 ? "发送成功" : "发送失败" }}</span>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <el-pagination
                    background
                    v-model:current-page="page"
                    v-model:page-size="pageSize"
                    :page-sizes="pageSizeNum"
                    :total="totalNums"
                    layout="total, sizes, prev, pager, next, jumper"
                >
                </el-pagination>
            </el-tab-pane>
        </el-tabs>
    </div>
    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, watch, onBeforeUnmount } from "vue"
import { useRouter } from "vue-router"
import { genFileId } from "element-plus"
import GoBack from "@components/GoBack.vue"
import OneLoad from "@mixins/one-load"
import TitleMore from "@components/title-more.vue"
import CellTip from "@components/cell-tip.vue"
import DetailItem from "@components/DetailItem.vue"

const router = useRouter()
const { proxy } = getCurrentInstance()

onMounted(() => {
    getSMSNums()
    getLevel()
})

onBeforeUnmount(() => {
    uploadFileRef.value = null
})

const tabName = ref("0")
const sms_nums = ref(0)
function getSMSNums() {
    proxy.$axios
        .get("sms/capital")
        .then((res) => {
            if (res.data.code == 0) {
                sms_nums.value = res.data.data.remain
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * 编辑短信
 * @param {String} sms_text 左侧显示短信内容
 * @param {String} sms_tel 表格显示内容
 * @param {String} radio_type 发送方式，0是平台会员，1是导入手机号
 * @param {String} contexts 编辑短信内容
 * @param {Array} sms_words 关键词数组，{插入昵称}，{插入店铺}...
 */
const sms_text = ref("")
const sms_tel = ref("")
const radio_type = ref("0")
const sms_words = ref([
    {
        type: 1,
        text: "{插入昵称}",
    },
    {
        type: 2,
        text: "{插入姓名}",
    },
    {
        type: 3,
        text: "{插入UID}",
    },
])
const radioChange = (val) => {
    radio_type.value = val
    contexts.value = ''
}
const clickWord = (item) => {
    sms_text.value = sms_text.value + item.text
}

// 发送
const btn_loading = ref(false)
const handleSend = () => {
    if (!level_id.value && radio_type.value == 0) {
        proxy.$message({ message: "请选择会员等级", type: "warning" })
        return
    }
    if (sms_text.value == "") {
        proxy.$message({ message: "请输入短信内容", type: "warning" })
        return
    }
    if (sms_tel.value == "" && radio_type.value == 1) {
        proxy.$message({ message: "手机号不能为空", type: "warning" })
        return
    }
    let last_symbol = sms_tel.value.substring(sms_tel.value.length, sms_tel.value.length - 1)
    if (last_symbol === "," || last_symbol === "，") {
        proxy.$message({ message: "手机号默认不能带有','号", type: "warning" })
        return
    }
    let content = sms_text.value
    if (sms_text.value.indexOf("回T退订") == -1) {
        content = sms_text.value + "，回T退订！"
    }
    postSend(content)
}
const postSend = (content) => {
    let datas = {
        send_type: radio_type.value, // 发送方式[0:平台会员,1:手机号导入]
        content,
        grade_id: radio_type.value == 1 ? 0 : level_id.value,
    }
    radio_type.value == 1 && (datas.mobiles = sms_tel.value)
    btn_loading.value = true
    proxy.$axios
        .post("sms/mass/send", datas)
        .then((res) => {
            btn_loading.value = false
            if (res.data.code == 0) {
                proxy.$message({ message: "发送成功", type: "success" })
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            btn_loading.value = false
        })
}

/**
 * 会员等级
 * @param {String} level_id 会员等级ID
 */
const level_id = ref("")
const level_arrs = ref([])
function getLevel() {
    proxy.$axios
        .get("user/search")
        .then((res) => {
            if (res.data.code == 0) {
                level_arrs.value = res.data.data.grade_list
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * 导入/导出商品-批量修改价格/库存
 * @param {Array} fileList_two 上传数组
 * @param {Function} actionImgUrl 阻止上传地址
 * @param {Function} handleRemove 文件状态移除时的钩子
 * @param {Function} fileChange 文件状态改变时的钩子
 * @param {Function} uploadFile 文件上传
 */
const uploadFileRef = ref(null)
const fileList_two = ref([])
const fileChange_two = (file, fileArr) => {
    fileList_two.value = fileArr
}
const handleExceed_two = (files) => {
    uploadFileRef.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadFileRef.value.handleStart(file)
}
const handleRemove_two = () => {
    fileList_two.value = []
}
const downExcel = () => {
    proxy.$axios
        .get("sms/mass/tmpl", {
            params: {},
            responseType: "blob",
        })
        .then(function (res) {
            let contentDisposition = res.headers["content-disposition"]
            let filename = decodeURI(contentDisposition.split("fileName=")[1] || contentDisposition.split("filename=")[1])
            let blob = new Blob([res.data], { type: res.headers["content-type"] })
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement("a")
            link.href = url
            link.download = filename
            document.body.appendChild(link)
            link.click()
            URL.revokeObjectURL(url) // 释放内存
            document.body.removeChild(link)
        })
        .catch((err) => {})
}
const uploadFile = () => {
    if (fileList_two.value.length == 0) {
        proxy.$message({ message: "请选择文件上传", type: "warning" })
        return
    }
    let data = new FormData()
    data.append("excel", fileList_two.value[0].raw)
    proxy.$axios
        .post("sms/mass/import", data)
        .then((res) => {
            fileList_two.value = []
            if (res.data.code == 0) {
                uploadFileRef.value.clearFiles()
                let result = res.data.data
                sms_tel.value = result.mobile_str
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
// 图片上传地址
function actionImgUrl() {
    return ""
}

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, totalNums, pubParams, pubRefreshParams, getdata } = OneLoad()
// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    pubParams(getList)
})

const clickTab = (pane) => {
    pane.index == 1 && pubRefreshParams(getList)
}
function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
    }
    getdata("sms/mass/log", params)
}

const clickRecharge = () => {
    router.push("/Marketing/RechargeSMS")
}
</script>
<script>
export default {
    name: "MassSMS",
}
</script>

<style lang="less" scoped>
.sms-btns {
    .sms-btns__box {
        display: flex;
    }
    :deep(.el-upload) {
        margin-right: @margin-sm;
    }
    :deep(.el-upload-list) {
        width: 460px;
    }
    .el-button {
        height: 30px;
        font-size: @font-size-sm;
    }
}
.tab-sms__word {
    display: flex;
    align-items: center;
    .tab-sms__word-item {
        flex: none;
        margin-right: 28px;
        color: @themes;
        cursor: pointer;
        &:hover {
            color: #0a64e8;
        }
    }
}
.tab-sms {
    display: flex;
    align-items: flex-start;
    .tab-sms__left {
        flex: none;
        width: 345px;
        border: 1px solid #ccc;
        border-radius: 15px;
        background: #fff;
        .tel-head {
            .tel-head-one {
                margin: 13px auto;
                width: 98px;
                height: 34px;
                // background: url("../../assets/images/a3.png") no-repeat;
                background: url("https://cdn.huashushop.com/tenant_593be52a46f869eea8b31d146d21de7a/album/202304/20230413_ee8387b5d7235673e18a963d25cfa0cf.png")
                    no-repeat;
                background-position: 0 -74px;
                display: block;
            }
            .tel-head-two {
                width: 320px;
                height: 64px;
                background: url("https://cdn.huashushop.com/tenant_593be52a46f869eea8b31d146d21de7a/album/202304/20230413_ee8387b5d7235673e18a963d25cfa0cf.png")
                    no-repeat;
                background-position: 0 0;
                color: #fff;
                overflow: hidden;
                border: 1px solid #22292c;
                border-bottom: 0;
                margin: 0 auto;
            }
        }
        .tel-body {
            margin: 0 auto;
            width: 320px;
            min-height: 400px;
            background-color: #f9f9f9;
            border: 1px solid #ccc;
            overflow: hidden;
            .tel-body-item {
                margin: @margin-mdl auto;
                width: 290px;
                color: #666;
                border: 1px solid @gray-3;
                font-size: @font-size-md;
                padding: @padding-sm;
                background-color: #fff;
            }
        }
        .tel-foot {
            margin: 10px auto;
            width: 62px;
            height: 61px;
            background: url("https://cdn.huashushop.com/tenant_593be52a46f869eea8b31d146d21de7a/album/202304/20230413_ee8387b5d7235673e18a963d25cfa0cf.png")
                no-repeat;
            background-position: -253px -70px;
        }
    }
    .tab-sms__right {
        margin-left: 25px;
        position: relative;
        border: 1px solid #e7e7eb;
        background-color: #f4f5f9;
        padding: 30px 4px 16px 12px;
        border-radius: 4px;
        width: 660px;
        .arrow {
            z-index: 10;
            position: absolute;
        }
        .arrow_out,
        .arrow_in {
            display: inline-block;
            width: 0;
            height: 0;
            border-width: 12px 12px 12px 0;
            border-style: dashed solid dashed dashed;
            margin-top: 0;
            top: 50px;
        }
        .arrow_out {
            border-color: transparent #e7e7eb transparent transparent;
            left: -13px;
        }
        .arrow_in {
            border-color: transparent #f4f5f9 transparent transparent;
            left: -12px;
        }
    }
}
.sms-textarea {
    :deep(.el-textarea__inner) {
        line-height: 1.6;
    }
}
:deep(.el-tabs__header) {
    margin-bottom: @margin-xl;
}
:deep(.el-radio) {
    height: auto;
}
.exp-detail {
    :deep(.detail-item__left) {
        line-height: 30px;
    }
}
.sms-one {
    position: relative;
    min-height: 24px;
    padding: 15px 20px;
    background: @gray-1;
    overflow: hidden;
    border-radius: @radius-sm;
    margin-bottom: @margin-mdl;
    strong {
        color: @red;
        font-size: @line-height-lg;
        margin-right: @margin-base;
    }
    .el-button {
        margin-left: @margin-sm;
    }
}
</style>
